using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Engine;
using Engine.Graphics;
using Game;

namespace RuthlessConquest {
    public static class IpLocationManager {
        public class Location {
            public string Country = string.Empty;

            public double QueryTime = double.MinValue;
        }

        public static Dictionary<IPAddress, Location> LocationsByAddress = new();
        public static double LastCleanupTime;
        public const string fName = "RCIpLocationManager";
        public static Texture2D GetFlagTexture(string countryCode) => ContentManager.Get<Texture2D>("RCTextures/Flags/" + countryCode, null, false);

        public static string GetCountryCode(IPAddress address) {
            double realTime = Time.RealTime;
            lock (LocationsByAddress) {
                if (realTime >= LastCleanupTime + 3600.0) {
                    LastCleanupTime = realTime;
                    int num = 0;
                    KeyValuePair<IPAddress, Location>[] array = LocationsByAddress.ToArray();
                    for (int i = 0; i < array.Length; i++) {
                        KeyValuePair<IPAddress, Location> keyValuePair = array[i];
                        if (realTime - keyValuePair.Value.QueryTime > 14400.0) {
                            LocationsByAddress.Remove(keyValuePair.Key);
                            num++;
                        }
                    }
                    if (num > 0) {
                        Log.Information(string.Format(LanguageControl.Get(fName, "1"), num, LocationsByAddress.Count));
                    }
                }
                if (!LocationsByAddress.TryGetValue(address, out Location location)) {
                    LocationsByAddress.Add(address, location = new Location());
                }
                if (!string.IsNullOrEmpty(location.Country)) {
                    return location.Country;
                }
                if (realTime - location.QueryTime < 30.0) {
                    return string.Empty;
                }
                location.QueryTime = realTime;
                Dictionary<string, string> dictionary = new();
                dictionary.Add("ip", address.ToString());
                WebManager.Get(
                    "http://iplocation.kaalus.com:30098/",
                    dictionary,
                    null,
                    null,
                    delegate(byte[] bytes) {
                        string @string = Encoding.UTF8.GetString(bytes);
                        if (@string.Length == 2) {
                            location.Country = @string;
                            Log.Information(string.Format(LanguageControl.Get(fName, "2"), address, @string));
                        }
                    },
                    delegate { }
                );
            }
            return string.Empty;
        }
    }
}